package com.weidey.blogWeb.utils;

import com.weidey.blogWeb.domain.WebCountRecord;
import com.weidey.blogWeb.mapper.WebCountRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component("syncCountersTask")
public class SyncCounters {

    @Autowired
    private WebCountRecordMapper webCountRecordMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Transactional
    public void syncCounters() {
        Set<String> keys = redisTemplate.keys("count:*");
        if (keys.isEmpty()) return;
        List<WebCountRecord> updateList = new ArrayList<>(5000);
        for (String key : keys) {
            try {
                Map<Object, Object> counts = redisTemplate.opsForHash().entries(key);
                String[] parts = key.split(":");
                Integer targetType = Integer.parseInt(parts[1]);
                Long targetId = Long.parseLong(parts[2]);

                counts.forEach((countTypeObj, countObj) -> {
                    String countTypeStr = (String) countTypeObj;
                    Integer countDelta = Integer.parseInt((String) countObj);

                    // 类型转换示例：将redis中的"like"转换为1
                    int countType = convertCountType(countTypeStr);
                    updateList.add(new WebCountRecord(
                            targetType,
                            targetId,
                            countType,
                            countDelta
                    ));
                });

                // 分批处理（每1000条提交一次）
                if (updateList.size() >= 1000) {
                    webCountRecordMapper.batchUpdateCounts(updateList);
                    updateList.clear();
                }
            } finally {
                redisTemplate.delete(key);
            }
        }
        // 处理剩余数据
        if (!updateList.isEmpty()) {
            webCountRecordMapper.batchUpdateCounts(updateList);
        }
    }


    private int convertCountType(String redisField) {
        switch (redisField) {
            case "like": return 1;
            case "star": return 2;
            case "follow": return 3;
            case "comment": return 4;
            default: throw new IllegalArgumentException("未知的计数类型");
        }
    }

}
